package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * Created with IntelliJ IDEA.
 * ClassName: PaymentService
 * Package: com.atguigu.springcloud.service
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-11-05
 * Time: 12:56
 */

@Service
public class PaymentService {

    //正常访问
    public String paymentInfo_OK(Integer id) {
        return "线程池: " + Thread.currentThread().getName() + "paymentInfo_OK" + id + "\t" + "O(∩_∩)O哈哈~";
    }


    //使用Hystrix进行服务降级 这个方法出事了 要有一个兜底的方法来处理
    //这个是使用的注解 还要在主启动添加@EnableCircuitBreaker
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="6000") //表示3秒之内都是正常的逻辑 超时了执行兜底的方法
    })
    public String paymentInfo_TimeOut(Integer id) {
        try {
            //若是出现
            //int age = 10/0; 效果也是一样的
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池: " + Thread.currentThread().getName() + "payment_TimeOut,id: " + id + "\t" + "O(∩_∩)O哈哈~" + "超时3秒";
    }

    public String paymentInfo_TimeOutHandler(Integer id) {
        return "兜底的方法111";
    }

    //=========服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id)
    {
        if(id < 0)
        {
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
    {
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~   id: " +id;
    }

}
